<?php
/**
 * @author      :   NguyenTT
 * @name        :   Plun_Plugin_Env
 * @todo        :   Envirement plugin
 */

define('XH_PROF_ENABLED', FALSE);
define('XH_PROF_NAMESPACE', 'plun');

class Plun_Plugin_Env extends Zend_Controller_Plugin_Abstract
{
    //Debug mode
    private $debug = 1;

    //Full mode
    private $full = 0;

    //Xhp mode
    private $xhp = 0;

    //Nolayout mode
    private $xnl = 0;

	/**
	 * Called before Zend_Controller_Front calls on the router
	 * to evaluate the request against the registered routes.
	 * @param Zend_Controller_Request_Abstract $request
	 */
	public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        //Get debug
        $this->debug = $request->getParam('debug', 0);
        $this->xhp = $request->getParam('xhp', 0);
        $this->full = $request->getParam('full', 0);
        $this->xnl = $request->getParam('xnl', 0);

        //Check xhp
        if($this->xhp)
        {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        }

        if (XH_PROF_ENABLED)
        {
            xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
        }
    }

    /**
     * Called after the router finishes routing the request.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function routeShutdown(Zend_Controller_Request_Abstract $request){}

    /**
     * Called before Zend_Controller_Front enters its dispatch loop.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $intUserId = 0;
        //Check login
        if (isset($_SESSION['uid']))
        {
            try
            {
                
            }
            catch (Exception $e)
            {
                 header('Location: /');
                 exit ();
            }

            //Set session UserId
            $_SESSION['uid'] = 1;
        }
        elseif ($intUserId == 0)
        {
            unset($_SESSION['uid']);
        }
        //////////////////////////////////////// END SSO ////////////////////////////////
        
        //Set parent params
        //Zend_Registry::set(PARENT_PARAMS_CONFIG, $request->getParams());

        //Get module
        $module = $request->getParam('module');

        //If empty then set default
        if(empty($module))
        {
            $module = 'default';
        }

        //Set module
        $module = strtolower($module);

        //Setup Include Paths
        set_include_path(implode(PATH_SEPARATOR,array(
            APPLICATION_PATH.DS.'modules'.DS.$module.DS.'models',
            get_include_path()
        )));

        //Get controller
        $controller = strtolower($request->getParam('controller'));

        //Get action
        $action = strtolower($request->getParam('action'));
        
        //Get application configuration
        $defaultConfiguration = Plun_Config::get('application');
        
        //Check module is backend
        if($module == 'backend')
        {
            //Get user info
            $this->_user = new Zend_Session_Namespace('admin');
            /*
            //Check authenticate
            if($_SESSION['user']['IsAdmin'] == 1 && $action != 'logout')
            {
                $login_successful = false;

                // check user & pwd:
                if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

                    $usr = $_SERVER['PHP_AUTH_USER'];
                    $pwd = $_SERVER['PHP_AUTH_PW'];

                    if ($usr == 'admin' && $pwd == '123456'){
                        $login_successful = true;
                    }
                }

                // login ok?
                if (!$login_successful){

                    // send 401 headers:
                    // realm="something" will be shown in the login box
                    header('WWW-Authenticate: Basic realm="Secret page"');
                    header('HTTP/1.0 401 Unauthorized');
                    print "Access denied!\n";exit;
                }
            }
            */
            if(!isset($_COOKIE['BEUSERNAME']) && isset($_SESSION['admin']))
            {
                $loginCookie = $_SESSION['admin']['UserID'].'_'.$_SESSION['admin']['username'].'_'.$_SESSION['admin']['IsAdmin'];
                setcookie("BEUSERNAME", $loginCookie,time() + 7200);
            }
            
            if(!isset($_SESSION['admin']) && ($_COOKIE['BEUSERNAME']!="0" || isset($_COOKIE['BEUSERNAME'])))
            {
                $arrCookieTemp = explode('_',$_COOKIE['BEUSERNAME']);
                if(count($arrCookieTemp)==3)
                {
                    $_SESSION['admin']['UserID'] = $arrCookieTemp[0];
                    $_SESSION['admin']['username'] = $arrCookieTemp[1];
                    $_SESSION['admin']['IsAdmin'] = $arrCookieTemp[2];
                }
                else
                {
                    $_COOKIE['BEUSERNAME'] = "0";
                }
            }
            
            //Check controller if login
            if($controller != 'login')
            {
                //Check info user is not logged in
                if(!$this->_user->username)
                {
                    $this->_response->setRedirect(BASE_URL . '/backend/login');
                    $this->_response->sendResponse(); exit();
                }
            }
            else
            {
                unset($this->_user);
            }

            //Layout setup
            $layoutInstance = Zend_Layout::startMvc(
                array(
                    'layout'     => 'layout',
                    'layoutPath' => APPLICATION_PATH.DS.'layouts'.DS.'backend',
                    'contentKey' => 'content'
                )
            );

            
        }
        else
        {
            //Check Lock Account
           

            //Get envirement
            $appEnv = APP_ENV;

            //Get global locales
            //$globalLocales = new Zend_Config_Ini(ROOT_PATH.'/locales/vietnamese.ini');

            //Set language
            //Zend_Registry::set(LOCALE_CONFIG, $globalLocales);

            //set layout default
            $layout = 'home';

            //check controller and layout
            if($controller != 'index')
            {
                $layout = 'layout';
            }

            //Layout setup
            $layoutInstance = Zend_Layout::startMvc(
                array(
                    'layout'     => $layout,
                    'layoutPath' => APPLICATION_PATH.DS.'layouts'.DS.'default',
                    'contentKey' => 'content'
                )
            );           
        }
        //Get current view
        $viewInstance = $layoutInstance->getView();

        //Set view title separator
        $viewInstance->doctype()->setDoctype('XHTML11');
        $viewInstance->headTitle()->setSeparator(' - ');

        //Add view phtml
        $viewInstance->addBasePath(APPLICATION_PATH .DS.'modules'.DS.$module.DS.'scripts'.DS.'views');

        //Set helpers path
        $viewInstance->addHelperPath(APPLICATION_PATH .DS.'layouts'.DS.'helpers');

        //Set partials path
        $viewInstance->addScriptPath(APPLICATION_PATH .DS.'layouts'.DS.'partials');

        //Register language and default configuration
        $this->addToView($viewInstance, 'static', $defaultConfiguration->static);
        //$this->addToView($viewInstance, 'api', $defaultConfiguration->api);
        //$this->addToView($viewInstance, 'locales', $globalLocales);
        //$this->addToView($viewInstance, 'env', APP_ENV);

        //Cleanup data
        unset($viewInstance);
    }

    /**
     * Called before an action is dispatched by the dispatcher.
     * This callback allows for proxy or filter behavior.
     * By altering the request and resetting its dispatched flag
     * via Zend_Controller_Request_Abstract::setDispatched(false),
     * the current action may be skipped and/or replaced.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request){}

    /**
     * Called after an action is dispatched by the dispatcher.
     * This callback allows for proxy or filter behavior.
     * By altering the request and resetting its dispatched flag
     * via Zend_Controller_Request_Abstract::setDispatched(false)),
     * a new action may be specified for dispatching.
     * @param Zend_Controller_Request_Abstract $request
     */
    public function postDispatch(Zend_Controller_Request_Abstract $request){}

    /**
     * Called after Zend_Controller_Front exits its dispatch loop.
     */
    public function dispatchLoopShutdown()
    {
        //Free all db connection to storage
        //Fpt_Global::closeAllDb();

        //Check debug
        if($this->debug)
        {
            //Get application configuration
            $configuration = Fpt_Global::getApplicationIni();
            $configuration = $configuration->caching->toArray();

            //Check towlevels
            $arrConfiguration = array();
            if(strtolower($configuration['adapter']) == 'twolevels')
            {
                $arrConfiguration[] = $configuration[$configuration['adapter']]['fast_backend']['profiler'];
                $arrConfiguration[] = $configuration[$configuration['adapter']]['slow_backend']['profiler'];
            }
            else
            {
                $arrConfiguration[] = $configuration['profiler'];
            }

            //Loop to get data
            $stringAppend = '';
            foreach($arrConfiguration as $profilerConfiguration)
            {
                //Get profiler
                $profiler = Fpt_Cache_Profiler::getInstance($profilerConfiguration);

                //Add body
                $stringAppend .= $profiler->getProfilerData();
            }

            //Append body
            $this->getResponse()->appendBody($stringAppend);
        }

        //Check xhp
        if($this->xhp)
        {
            //Get debug data xhprof
            $xhprof_data = xhprof_disable();
            $stringAppend = Fpt_Utility::getXhp($xhprof_data);

            //Append body
            $this->getResponse()->appendBody($stringAppend);
            }

            if (XH_PROF_ENABLED)
            {
            // stop profiler
            $xhprof_data = xhprof_disable();
            if (!defined('XHPROF_LIB_ROOT'))
            {
                define('XHPROF_LIB_ROOT', DOCUMENT_ROOT);
            }

            global $_xhprof; //global config for xhprof_lib

            include_once XHPROF_LIB_ROOT . "/xhprof_lib/config.php";
            include_once XHPROF_LIB_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
            include_once XHPROF_LIB_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

            // save raw data for this profiler run using default implementation of iXHProfRuns.
            $xhprof_runs = new XHProfRuns_Default();
            $xhprof_runs->save_run($xhprof_data, XH_PROF_NAMESPACE);
        }

        //Strip output buffer
        $output = $this->getResponse()->getBody();

        //Strip buffer
        if(!$this->full)
        {
            $output = $output;//Fpt_Filter::stripBuffer($output);
        }

        //Set body
        $this->getResponse()->setBody((string)$output);

        //Output data
        if(APP_ENV == "production")
        {
            echo $output; exit();
        }
    }

    /**
     * Add key and value which registered to view
     * @param <Zend_View> $view
     * @param <string> $key
     * @param <object> $value
     */
    private function addToView(&$view, $key, $value)
    {
        $view->$key = $value;
    }
}

